define(function(require, exports, module) {
	module.exports = {
		init : function(url){
			this.url = url;
			
			var panel = document.querySelector('.upload_panel');
			this.panel = panel;
			var fileEl = panel.$('input[type=file]');
			fileEl.onchange = onfileSelected.bind(this);
			this.fileEl = fileEl;
			
			this.xhr = new XMLHttpRequest();
			
			// 上传文件
			panel.$('.upload').$(uploadFile.bind(this));

			// 取消上传
			panel.$('.cancel').$(cancleUploadFile.bind(this));
		}
	};
	
	// 监听选择文件信息
	function onfileSelected(e) {
		// HTML5文件API操作
		var file = e.target;
		var fileSize = 0;
		
		if (file.size > 1024 * 1024)
			fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
		else
			fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
		
//		this.panel.$('.fileName').innerHTML = 'Name: ' + file.name;
//		this.panel.$('.fileSize').innerHTML = 'Size: ' + fileSize;
//		this.panel.$('.fileType').innerHTML = 'Type: ' + file.type;
	}
	
	function uploadFile(e) {
		e.preventDefault();
		var fd = new FormData();
		//关联表单数据,可以是自定义参数
//		fd.append("name", document.getElementById('name').value);
		fd.append("fileName", this.fileEl.files[0]);
		
		// 监听事件
		var xhr = this.xhr;
		xhr.upload.addEventListener("progress", uploadProgress.bind(this), false);
		xhr.addEventListener("load", uploadComplete, false);
		xhr.addEventListener("error", uploadFailed, false);
		xhr.addEventListener("abort", uploadCanceled, false);
		// 发送文件和表单自定义参数
		xhr.open("POST", this.url);
		xhr.send(fd);
	}

	function cancleUploadFile(e) {
		e.preventDefault();
		this.xhr.abort();
	}
	
	// 上传进度
	function uploadProgress(evt) {
		var progressNumber = this.panel.$('.progressNumber');

		if (evt.lengthComputable) {
			var percentComplete = Math.round(evt.loaded * 100 / evt.total);
			progressNumber.innerHTML = percentComplete.toString()+ '%';
		} else {
			progressNumber.innerHTML = 'unable to compute';
		}
	}
	
	// 上传成功响应
	function uploadComplete(evt) {
		//服务断接收完文件返回的结果
		
		alert('上传成功！' + evt.target.responseText);
	}
		
	// 上传失败
	function uploadFailed(evt) {
		alert("上传失败");
	}
	// 取消上传
	function uploadCanceled(evt) {
		alert("您取消了本次上传.");
	}
});



 
 


